import axios from 'axios'

import store from 'utils/vuex.js'

//loadding start
import {
  Message,
  Loading
} from 'element-plus';

let loading 
let needLoadingRequestCount = 0 // 需要加载的请求数，为 0 时取消加载动画

function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        loading = Loading.service({
            lock: true,
            spinner: 'el-icon-loading',
            text: 'Loading...',
            background: 'rgba(255, 255, 255, 0.5)'
        })
    }
    needLoadingRequestCount++
}

function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return

    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        loading.close()
    }
}

// 创建axios实例
let baseUrl;
if (process.env.VUE_APP_ENV === 'dev') {
    // baseUrl = 'http://192.168.19.176:9106' // 测试环境
} else if (process.env.VUE_APP_ENV === 'test') {
    baseUrl = 'http://192.168.19.176:9106'
} else if (process.env.VUE_APP_ENV === 'uat') {
    baseUrl = 'http://192.168.150.143:9103'
} else {
  throw Error('错误环境')
}

const service = axios.create({
        // xhrFields: {
        //   withCredentials: true
        // },
        // crossDomain: true,
        baseURL: baseUrl, // api的base_url
        timeout: 60000, // 请求超时时间,
        // withCredentials: true, //允许携带cookie
        changeOrigin: true
    })
    // request拦截器
service.interceptors.request.use(config => {
    if (config.url != '/userLogin/price/notify' && config.url != '/notify/notifyRecord/listByPage') {
        const getAuthorization = store.state.token;
        if (getAuthorization) {
            config.headers['token'] = getAuthorization; // 让每个请求携带自定义
        }
    }
    showFullScreenLoading();

    return config
}, error => {
    // loading.close()
    if(error.response) {
        handleError(error.response.status + '')
        return Promise.reject('\n' + error.response.status + ': ' + error.response.config.url)
    } else {
        handleError('unknown')
        return Promise.reject('\n' + error)
    }
    // return error
})

// respone拦截器
service.interceptors.response.use(response => {
    tryHideFullScreenLoading()
    if (response.data.code == '200') {
        return response.data
    } else if(response.data.code) {
        handleError(response.data.code)
        return Promise.reject('\n' + response.data.code + ': ' + response.config.url)
    } else {
        console.log(response)
        return response
    }
}, error => {
    // console.dir(error);
    loading.close()
    tryHideFullScreenLoading()
    if(error.response) {
        handleError(error.response.status + '')
        return Promise.reject('\n' + error.response.status + ': ' + error.response.config.url)
    } else {
        handleError('unknown')
        return Promise.reject('\n' + error)
    }
    
})

export default service

//get方法
export function GET(url, data, config = {}) {
    for(var key in data) {
        if(typeof data[key] == 'string') {
            data[key] = data[key].trim()
            if(data[key] === '') {
                data[key] = undefined 
            }
        }
    }
    data.t = new Date().getTime() // 防止IE缓存get请求
    return service({
        url: url,
        method: 'get',
        params: data,
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
        },
        ...config,
    })
}
//post方法
export function POST(url, data, config = {}) {
    for(var key in data) {
        if(typeof data[key] == 'string') {
            data[key] = data[key].trim()
            if(data[key] === '') {
                data[key] = undefined 
            }
        }
    }
    return service({
        url: url,
        method: 'post',
        data: data,
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
        },
        ...config,
    })
}
//delete方法
export function DELETE(url, data, config = {}) {
    for(var key in data) {
        if(typeof data[key] == 'string') {
            data[key] = data[key].trim()
            if(data[key] === '') {
                data[key] = undefined 
            }
        }
    }
    return service({
        url: url,
        method: 'delete',
        data: data,
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
        },
        ...config,
    })
}
//put方法
export function PUT(url, data, config = {}) {
    for(var key in data) {
        if(typeof data[key] == 'string') {
            data[key] = data[key].trim()
            if(data[key] === '') {
                data[key] = undefined 
            }
        }
    }
    return service({
        url: url,
        method: 'put',
        data: data,
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
        },
        ...config,
    })
    // .then(function(response) {
    //     if (response.data.code == '200') {
    //         return response.data
    //     } else {
    //         handleError(response.data.code || response.status)
    //     }
    // })
}

//post类型 file 下载
/**
 * 
 * @param {string} url 地址
 * @param {object | array} data 数据
 * @param {object} config 私有的 axios 配置
 * @param {boolean} flag 是否需要进行url解码（一般文件名有中文时，后端会对其进行url编码） 
 */
export function Download(url, data, config = {}, flag) {
    for(var key in data) {
        if(typeof data[key] == 'string') {
            data[key] = data[key].trim()
            if(data[key] === '') {
                data[key] = undefined 
            }
        }
    }
    return service({
        url: url,
        method: 'post',
        data: data,
        responseType: 'blob',
        timeout: 600000,
        headers: {
            'Content-Type': 'application/json;charset=UTF-8',
        },
        ...config,
    }).then(function(response) {
        if (response.status == '200') {
            var blob = new Blob([response.data])
            try {
                var filename = response.headers['content-disposition'].split('=')[1]
            } catch (e) {
                console.error('缺少响应头 content-disposition ')
            }
            if(flag) {
                filename = decodeURI(filename)
            }
            if (window.navigator.msSaveBlob) {
                // IE
                try {
                    window.navigator.msSaveBlob(blob, filename)
                } catch (e) {
                    console.log(e);
                }
            } else {
                // 谷歌
                let url = window.URL.createObjectURL(blob)

                let link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.download = filename
        
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)

                window.URL.revokeObjectURL(url); //释放掉blob对象
            }
        } else {
            handleError(response.data.code || response.status)
        }
    })
}

//post类型 formdata 上傳
export function Upload(url, data, config = {}) {
    return service({
        url: url,
        method: 'post',
        data: data,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        ...config,
    })
}

function handleError(code) {
    var message = '';
    switch (code) {
        case '-1':
            message = '錯誤！';
            break;
        default:
            message = '網絡超時！';
            break;
    }
    Message({
        message: message,
        type: 'error',
        duration: 2 * 1000
    })
}